package com.sigmatrix.h5.service.impl;

import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import com.alibaba.fastjson.JSONObject;
import com.sigmatrix.h5.components.FeignManager;
import com.sigmatrix.h5.components.RedisClient;
import com.sigmatrix.h5.dao.EnterpriseDao;
import com.sigmatrix.h5.entity.DisDealerAcct;
import com.sigmatrix.h5.entity.DisRoleRes;
import com.sigmatrix.h5.entity.DisSysResDetail;
import com.sigmatrix.h5.entity.Enterprise;
import com.sigmatrix.h5.entity.Users;
import com.sigmatrix.h5.enums.CrmAcctType;
import com.sigmatrix.h5.enums.RebateTarget;
import com.sigmatrix.h5.enums.SysResModule;
import com.sigmatrix.h5.enums.UserType;
import com.sigmatrix.h5.enums.WalletType;
import com.sigmatrix.h5.exception.MessageException;
import com.sigmatrix.h5.feign.mode.CoinDto;
import com.sigmatrix.h5.feign.mode.WechatAuthorizerConfig;
import com.sigmatrix.h5.service.DisDealerAcctService;
import com.sigmatrix.h5.service.DisSysResDetailService;
import com.sigmatrix.h5.service.UsersService;
import com.sigmatrix.h5.utils.Assert;
import com.sigmatrix.h5.utils.CommonUtils;
import com.sigmatrix.h5.utils.MD5Utils;
import com.sigmatrix.h5.utils.SessionUtils;
import com.sigmatrix.h5.utils.VerificationCodeUtils;
import com.sigmatrix.h5.web.mode.Login;
import com.sigmatrix.h5.web.mode.VerCode;
import com.sigmatrix.sc.jdbc.common.lang.Session;
import com.sigmatrix.sc.jdbc.common.service.ServiceImpl;
/**
 * 
 *@ClassName: UsersServiceImpl
 *@Description: 平台账号
 *@author MH
 *@date 2017年9月22日 上午10:19:25
 */
@Service
public class UsersServiceImpl extends ServiceImpl<Users,Integer> implements UsersService{
	@Autowired
	private EnterpriseDao enterpriseDao;
	@Autowired
	private FeignManager feignClients;
	@Autowired
	private RedisClient redisClient;
	@Autowired
	private DisDealerAcctService disDealersAcctService;
	@Autowired
	private DisSysResDetailService disSysResDetailService;
	@Override
	public Login login(String loginName, String loginPwd,SysResModule module) {
//		Assert.notNull(loginName, loginPwd, "账号/密码不能为空");
		//验证登录
		DisDealerAcct acct = disDealersAcctService.findByUserName(loginName);
		Assert.notNull(acct, "账号错误,没有此用户");
		if(!MD5Utils.getMD5Code(loginPwd).equals(acct.getPwd()))throw new MessageException("密码错误");
		Assert.notNull(acct.getEnterpriseId(), "无效的用户,企业id为空");
		Assert.notNull(acct.getName(), "无效的用户,姓名为空");
		Login login = new Login();
		BeanUtils.copyProperties(acct, login);
		login.setUserId(acct.getId());
		login.setAccount(loginName);
		login.setEseId(acct.getEnterpriseId());
		login.setPhoneNumber(acct.getContact());
		getEnterprise(login);
		login.setTablePreffix(login.getEseCode());
		login.setDealersAcctPromotionCode(acct.getDealersAcctPromotionCode());

		switch (module) {
		case REBATE:
			rebateLogin(login,acct);
			break;
		default:
			WechatAuthorizerConfig wechatConfig = feignClients.getAppId(login.getBasicModuleEseId().longValue());
			Assert.notNull(wechatConfig, "获取appId失败");
			Assert.notNull(wechatConfig.getAuthorizerAppId(), "appId为空");
			login.setAppId(wechatConfig.getAuthorizerAppId());
			break;
		}
		//保存token
		String token = MD5Utils.getMD5Code(System.currentTimeMillis()+loginName);
		login.setToken(token);
		redisClient.set(token, JSONObject.toJSONString(login));
		return login;
	}
	/**
	 * 
	 *@Title: getEnterprise
	 *@Description:登录时获取企业信息
	 *@return void
	 *@author MH
	 *@date 2018年1月24日 下午2:47:16
	 *@param login
	 */
	private void getEnterprise(Login login) {
		Enterprise enterprise = enterpriseDao.findById(login.getEseId());
		Assert.notNull(enterprise, "无效的用户,企业ID错误");
		Assert.notNull(enterprise.getBasicModuleId(), "无效的企业,basicMoudleId为空");
		Assert.notNull(enterprise.getCode(), "无效的企业,code为空");
		login.setEseCode(enterprise.getCode());
		login.setBasicModuleEseId(enterprise.getBasicModuleId());
		login.setEseName(enterprise.getName());
	}
	/**
	 * 
	 *@Title: rebateLogin
	 *@Description:返利登录获取零钱包参数
	 *@return void
	 *@author MH
	 *@date 2018年1月24日 下午2:47:29
	 *@param login
	 *@param roleRes
	 */
	private void rebateLogin(Login login,DisDealerAcct acct) {
		//先校验权限
		Session.set(login);
		
		if(CrmAcctType.TERMINAL_SHOP.value.equals(login.getAcctType())) {
			login.setDealerType(RebateTarget.TERMINAL_SHOP.value);
		}else if(CrmAcctType.ENTERPRISE.value.equals(login.getAcctType())){
			login.setDealerType(RebateTarget.SALES_MAN.value);
		}else {
			Short userType = acct.getUserType();
			if(userType==null){
				login.setDealerType(RebateTarget.SALES_MAN.value);
			}else if(UserType.ADMIN.value.equals(userType)){
				login.setDealerType(RebateTarget.DEALER.value);
			}else{
				login.setDealerType(RebateTarget.SALES_MAN.value);
			}
		}
		
		//获取零钱包参数
		CoinDto dto = feignClients.findCoin(login.getBasicModuleEseId());
		if(CommonUtils.isNotEmpty(dto)){
			login.setAppId(dto.getToAppId());
			login.setMaxCount(dto.getMaxAmount()==null?0D:dto.getMaxAmount().doubleValue()*0.01);
			login.setMinCount(dto.getMinAmount()==null?0D:dto.getMinAmount().doubleValue()*0.01);
			login.setMinUnit(dto.getMinUnit()==null?0D:dto.getMinUnit().doubleValue()*0.01);
		}
		Session.clear();
	}
	@Override
	public VerCode generateVerCode() {
		String value = UUID.randomUUID().toString().substring(0,4);
		byte[] bs = VerificationCodeUtils.drawImage(value);
		VerCode code = new VerCode();
		code.setImage(Base64Utils.encodeToString(bs));
		code.setValue(value);
		return code;
	}

	@Override
	public void logout(String token) {
		redisClient.delete(token);
		
	}
	@Override
	public DisDealerAcct findByAcctAndPwd(String acct, String pwd) {
		DisDealerAcct user = disDealersAcctService.findByUserName(acct);
		Assert.notNull(user, "账号错误");
		if(MD5Utils.getMD5Code(pwd).equals(user.getPwd())){
			Enterprise enterprise = enterpriseDao.findById(user.getEnterpriseId());
			Assert.notNull(enterprise, "账号异常,企业不对");
			user.setBasicModuleId(enterprise.getBasicModuleId());
			return user;
		}
		throw new MessageException("密码错误");
	}
	@Override
	public void updatePwdByAcct(String acct, String pwd) {
		//TODO 时间紧急就不写sql了，以后再优化
		Assert.notNull(acct, pwd, "账号密码不能为空");
		DisDealerAcct user = disDealersAcctService.findByUserName(acct);
		Assert.notNull(user, "账号错误，修改密码失败");
		DisDealerAcct po = new DisDealerAcct();
		po.setId(user.getId());
		po.setPwd(MD5Utils.getMD5Code(pwd));
		disDealersAcctService.updateSelective(po);
	}

}
